package com.yrd.centerlogclient;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingDeque;

import org.zeromq.ZMQ;

import com.rzrk.centerlog.entity.NormalLog;

public class Sender {
	boolean alive;
	BlockingQueue<String> queue;
	ZMQ.Context context;
	ZMQ.Socket socket;
	Thread thread;
	
	private static Sender sender;
	
	public static Sender createInstance(String url,long hwm){
		if(sender!=null){
			sender.stop();
		}
		sender = new Sender(url,hwm);
		return sender;
	}
	
	public static Sender getInstance(){
		return sender;
	}
	
	public Sender(String url,long hwm) {
		alive=true;
		queue = new LinkedBlockingDeque<String>();
		context = ZMQ.context(1);
		socket = context.socket(ZMQ.PUB);
		socket.setSndHWM(hwm);
		socket.connect(url);
		
		thread = new Thread(new Runnable() {
			public void run() {
		    	while(alive){
		    		try {
		    			String msg = queue.take();
			    		socket.send(msg);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
		    	}
		    	socket.close();
		    	context.close();
			}
		});
		thread.start();
		

	}
	
	public void stop(){
		alive=false;
		thread.interrupt();
	};
	
	
	public void post(String msg){
		queue.add(msg);
	}

	
	public void postNormal(String msg){
		post(NormalLog.Tag+"\n"+msg);
	}
	
}
